/* 导入组件
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaImport\List\components\ImportExcel.tsx
 * @Date: 2021-09-18 14:51:27
 * @LastEditTime: 2021-09-18 15:02:21
 */

import { Button, Input, message, Row, Select, Spin, Upload } from 'antd'
import React, { createRef } from 'react'
import quotaApis from '@/apis/AboutQuota'
import todoApi from '@/apis/TodoList/index'
import { downBlobFile, downBlobFileXlsx } from '@/utils/methods'
import { http, IUdFormItem, UdForm, validators } from '@/lib'
import QuotaApprove from '@/components/getQuotaApprove'
import './approve.scss'
import ossHttp from '@/utils/oss'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import TextArea from 'antd/lib/input/TextArea'
// import UdUploader from '@/components/UdUploader/Uploader'

const { Option } = Select

export default class ImportExcel extends React.Component<any> {
  private data = { ...(this.props.data ?? {}) }
  private modifyType = { ...(this.props.modifyType ?? '') }
  private STAGE_STATUS_ENUM = {
    EXECUTED: '已执行',
    EXECUTION: '执行中',
    UNEXECUTED: '待执行',
  }
  private labelCol: any = { span: 3 }
  public cRef = createRef<any>()
  private templateUrl = {
    QUOTACHANGE: quotaApis.getOutQuotaAdjustTemplate,
    ACTUAL: quotaApis.getActualTemplate,
    Customers: quotaApis.getCustomersTemplate,
  }
  form: WrappedFormUtils
  state = {
    fileList: [],
    fileCertificateList: [],
    downloading: false,
    workFlowList: [],
    checkPerson: [],
    uploading: false,
    isApprove: {
      quotaImport: false,
    },
  }

  componentDidMount() {
    let params = { brandCode: this.data.record['brandCode'], prodBarcode: this.data.record['prodBarcode'] }
    http.get(todoApi.getProcessKeyFlow, { params }).then(res => {
      this.setState({
        isApprove: res.data,
      })
    })
    this.getWorkFlow()
  }

  //上传前操作
  private beforeUpload = file => {
    console.log('file', file)
    if (this.state.fileList.length === 0) {
      const fileItem = {
        file,
        uid: file.uid,
        name: file.name,
        status: 'uploading',
        url: '',
      }
      ossHttp.put('settled-review/annex', file).then(res => {
        fileItem.url = res.url
        fileItem.status = 'done'
        this.setState({ fileList: [fileItem] })
      })
    } else {
      message.error('只能上传一个文件')
    }
    return false
  }

  //删除文件
  private onRemove = file => {
    let fileList = this.state?.fileList ?? []
    fileList = fileList.filter(fileItem => fileItem.uid !== file.uid)
    this.setState({ fileList }, () => {
      return true
    })
  }

  //上传附件前操作
  private beforefileCertificateUpload = file => {
    console.log('file', file)
    if (this.state.fileCertificateList.length < 3) {
      const fileItem = {
        file,
        uid: file.uid,
        name: file.name,
        status: 'uploading',
        url: '',
      }
      ossHttp.put('settled-review/annex', file).then(res => {
        fileItem.url = res.url
        fileItem.status = 'done'
        this.setState({ fileCertificateList: [...this.state.fileCertificateList, fileItem] })
      })
    } else {
      message.error('只能上传3个文件')
    }
    return false
  }

  //删除附件文件
  private onfileCertificateRemove = file => {
    let fileCertificateList = this.state?.fileCertificateList ?? []
    fileCertificateList = fileCertificateList.filter(fileItem => fileItem.uid !== file.uid)
    this.setState({ fileCertificateList }, () => {
      return true
    })
  }

  //下载模板
  private downloadTemplate = ({ record, modifyType, name }: any) => {
    this.setState({ downloading: true })
    let url = ''
    let param = {}
    if (modifyType) {
      url = this.templateUrl[modifyType]
      param = { modifyType }
    } else {
      url = this.templateUrl['Customers']
      let customerTemplateType = this.form.getFieldValue('customerTemplateType')
      if (customerTemplateType === 'MODULATION') {
        name = '客户配额调整模板'
      } else {
        name = '客户间配额调整模版'
      }
      param = { modifyType: customerTemplateType }
    }
    http
      .get(url, { params: { id: record.id, ...param }, responseType: 'arraybuffer' })
      .then(res => {
        if (!res.data.code) {
          downBlobFileXlsx(res.data, name)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  //获取审批角色
  private getWorkFlow = () => {
    http.get(todoApi.getQuotaImportNextApprove, { params: { brandCode: this.data.record['brandCode'] } }).then(res => {
      const { data } = res
      this.setState({ workFlowList: data })
    })
  }

  //选择审批人
  private handShowQuotaApprove(index) {
    this.cRef.current.handelCeck(index)
  }

  private handGetPerson(value) {
    this.setState({ checkPerson: value })
  }

  private onOk = e => {
    this.form.validateFields((err, values) => {
      if (!err) {
        const {remark} = values
        const { record, modifyType, name } = this.data
        const { fileList, fileCertificateList } = this.state
        if (fileList.length === 0) {
          message.warn('请选择导入文件')
          return false
        }
        if (this.state.isApprove?.quotaImport && this.state.checkPerson.length === 0) {
          message.warn('请选择审批人')
          return false
        }
        this.setState({ uploading: true })
        e.drawerBtnLoading()
        const formData = new FormData()
        let url = ''
        formData.append('file', fileList[0].file)
        let params: any = { id: record.id }
        if (this.state.checkPerson.length > 0) {
          params['workflowReqVos'] = {
            name: 'candidateUsers',
            userId: [this.state.checkPerson[0].id],
          }
        }
        if (modifyType) {
          if (modifyType === 'QUOTACHANGE') {
            url = quotaApis.quotaYearTransmitImport
          } else if (modifyType === 'ACTUAL') {
            //导入实际配额增加备注
            url = quotaApis.quotaStageTransmitImport
            params['remark']=remark
          }
        } else {
          url = quotaApis.quotaReadjustTransmitImport
          let customerTemplateType = this.form.getFieldValue('customerTemplateType')
          params['matter'] = customerTemplateType
          //导入配额调整增加备注
          params['remark']=remark
        }

        params['quotaApplyDetailFileRespVoList'] = [{ name: fileList[0].name, url: fileList[0].url }]
        params['quotaApplyDetailCertificateRespVoList'] = [
          ...fileCertificateList.map(r => {
            return { name: r.name, url: r.url }
          }),
        ]

        formData.append('quotaApplyExcelHistoryReqVo', new Blob([JSON.stringify(params)], { type: 'application/json' }))
        http
          .post(url, formData, { timeout: 1000 * 60 * 10 })
          .then(() => {
            message.success('操作成功')
            this.props.refresh()
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
          .finally(() => {
            this.setState({ uploading: false })
          })
      } else {
        console.log(err)
      }
    })
  }

  render() {
    const { record, modifyType, name } = this.data
    record.term = record.stageBeginTime && record.stageEndTime ? `${record.stageBeginTime}-${record.stageEndTime}` : ''
    let TipsNode = null
    let items: IUdFormItem[] = []
    if (modifyType) {
      if (modifyType === 'QUOTACHANGE') {
        TipsNode = (
          <Row style={{ marginTop: 20, marginBottom: 20, fontSize: 12 }}>
            <Row>备注信息</Row>
            <Row style={{ marginTop: 10 }}>1：客户执行中状态标准配额为空时，可上传执行中和待执行考核阶段的数据。</Row>
            <Row style={{ marginTop: 10 }}>
              2：客户执行中状态标准配额不为空时，只能上传待执行考核阶段的数据，覆盖原有的数据。
            </Row>
          </Row>
        )
        items = [
          { id: 'brandName', label: '品牌公司', render: <Input readOnly /> },
          { id: 'prodBarname', label: '配额品项', render: <Input readOnly /> },
          { id: 'stageYear', label: '考核年度', render: <Input readOnly /> },
          {
            id: 'fileTemplate',
            label: '客户模板',
            render: (
              <Button
                type="primary"
                onClick={() => {
                  this.downloadTemplate(this.data)
                }}
              >
                下载模板
              </Button>
            ),
          },
          {
            id: 'fileUpload',
            label: '导入文件',
            render: (
              <Upload
                showUploadList={true}
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                fileList={this.state.fileList}
                beforeUpload={file => this.beforeUpload(file)}
                onRemove={file => this.onRemove(file)}
              >
                <Button type="primary">上传文件</Button>
              </Upload>
            ),
          },
          {
            id: 'fileCertificate',
            label: '附件',
            render: (
              <Upload
                showUploadList={true}
                accept="image/jpg,image/jpeg,image/png,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/msword"
                fileList={this.state.fileCertificateList}
                beforeUpload={file => this.beforefileCertificateUpload(file)}
                onRemove={file => this.onfileCertificateRemove(file)}
              >
                <Button type="primary">上传附件</Button>
                <div className="ud-uploader-extra">支持扩展名：.jpg .png .xls .doc</div>
              </Upload>
            ),
          },
        ]
      } else if (modifyType === 'ACTUAL') {
        record.stageStatusText = this.STAGE_STATUS_ENUM[record.stageStatus]
        items = [
          { id: 'brandName', label: '品牌公司', render: <Input readOnly /> },
          { id: 'prodBarname', label: '配额品项', render: <Input readOnly /> },
          { id: 'belongAreaName', label: '片区', render: <Input readOnly /> },
          { id: 'stageYear', label: '考核年度', render: <Input readOnly /> },
          { id: 'stageName', label: '考核阶段', render: <Input readOnly /> },
          { id: 'term', label: '配额有效期', render: <Input readOnly /> },
          { id: 'stageStatusText', label: '状态', render: <Input readOnly /> },
          {
            label: '备注信息',
            id: 'remark',
            // rules: [validators.required],
            render: <TextArea rows={3} maxLength={200} />,
          },
          {
            id: 'fileTemplate',
            label: '客户模板',
            render: (
              <Button
                type="primary"
                onClick={() => {
                  this.downloadTemplate(this.data)
                }}
              >
                下载模板
              </Button>
            ),
          },
          {
            id: 'fileUpload',
            label: '导入文件',
            render: (
              <Upload
                showUploadList={true}
                accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                fileList={this.state.fileList}
                beforeUpload={file => this.beforeUpload(file)}
                onRemove={file => this.onRemove(file)}
              >
                <Button type="primary">上传文件</Button>
              </Upload>
            ),
          },
          {
            id: 'fileCertificate',
            label: '附件',
            render: (
              <Upload
                showUploadList={true}
                accept="image/jpg,image/jpeg,image/png,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/msword"
                fileList={this.state.fileCertificateList}
                beforeUpload={file => this.beforefileCertificateUpload(file)}
                onRemove={file => this.onfileCertificateRemove(file)}
              >
                <Button type="primary">上传附件</Button>
                <div className="ud-uploader-extra">支持扩展名：.jpg .png .xls .doc</div>
              </Upload>
            ),
          },
        ]
        TipsNode = (
          <Row style={{ marginTop: 20, marginBottom: 20, fontSize: 12 }}>
            <Row>备注信息</Row>
            <Row style={{ marginTop: 10 }}>1：执行中状态，只能导入一次</Row>
            <Row style={{ marginTop: 10 }}>2：待执行状态，不限制导入次数。</Row>
          </Row>
        )
      }
    } else {
      record.customerTemplateType = 'MODULATION'
      items = [
        { id: 'brandName', label: '品牌公司', render: <Input readOnly /> },
        { id: 'prodBarname', label: '配额品项', render: <Input readOnly /> },
        { id: 'belongAreaName', label: '片区', render: <Input readOnly /> },
        { id: 'stageYear', label: '考核年度', render: <Input readOnly /> },
        { id: 'stageName', label: '考核阶段', render: <Input readOnly /> },
        { id: 'term', label: '配额有效期', render: <Input readOnly /> },
        {
          label: '备注信息',
          id: 'remark',
          // rules: [validators.required],
          render: <TextArea rows={3} maxLength={200} />,
        },
        {
          id: 'customerTemplateType',
          label: '选择模板',
          render: (
            <Select style={{ width: '100%' }}>
              <Option value="MODULATION">客户配额调整</Option>
              <Option value="ADJUSTMENT">客户间配额调整</Option>
            </Select>
          ),
        },
        {
          id: 'fileTemplate',
          label: '客户模板',
          render: (
            <Button
              type="primary"
              onClick={() => {
                this.downloadTemplate(this.data)
              }}
            >
              下载模板
            </Button>
          ),
        },
        {
          id: 'fileUpload',
          label: '导入文件',
          render: (
            <Upload
              showUploadList={true}
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              fileList={this.state.fileList}
              beforeUpload={file => this.beforeUpload(file)}
              onRemove={file => this.onRemove(file)}
            >
              <Button type="primary">上传文件</Button>
            </Upload>
          ),
        },
        {
          id: 'fileCertificate',
          label: '附件',
          render: (
            <Upload
              showUploadList={true}
              accept="image/jpg,image/jpeg,image/png,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel,application/msword"
              fileList={this.state.fileCertificateList}
              beforeUpload={file => this.beforefileCertificateUpload(file)}
              onRemove={file => this.onfileCertificateRemove(file)}
            >
              <Button type="primary">上传附件</Button>
              <div className="ud-uploader-extra">支持扩展名：.jpg .png .xls .doc</div>
            </Upload>
          ),
        },
      ]
      TipsNode = (
        <Row style={{ marginTop: 20, marginBottom: 20, fontSize: 12 }}>
          <Row>导入说明</Row>
          <Row style={{ marginTop: 10 }}>
            1：选择类型为客户配额调整，根据客户配额调整模板下载已导入该考核阶段实际配额的客户信息和数据信息。
          </Row>
          <Row style={{ marginTop: 10 }}>2：选择类型为客户间配额调整，只下载模板。</Row>
        </Row>
      )
    }
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '下载中，请稍后...'}
      >
        <UdForm getForm={form => (this.form = form)} values={record} labelCol={this.labelCol} items={items} />
        {TipsNode}
        {this.state.isApprove?.quotaImport && <h4>审批流程</h4>}
        {this.state.isApprove?.quotaImport && (
          <div className="approve-wrap">
            <div className="node-name-wrap">
              <div className="approve-title">节点名称：</div>
              <span className="circle-point"></span>
              <div>{this.state.workFlowList[0]?.nodeName || '暂无流程模板'}</div>
            </div>
            <div className="person-name-wrap">
              <div className="approve-title">审批人:</div>
              <div
                className={this.state.checkPerson[0]?.realName ? 'add-plus-name' : 'add-plus'}
                onClick={() => {
                  this.state.workFlowList[0] ? this.handShowQuotaApprove(0) : (() => {})()
                }}
              >
                {this.state.checkPerson[0]?.realName || '+'}
              </div>
            </div>
          </div>
        )}
        <QuotaApprove
          handCilck={this.handGetPerson.bind(this)}
          cRef={this.cRef}
          ids={this.state.workFlowList[0]?.roleIds}
        />
      </Spin>
    )
  }
}
